package com.isoft.c2team3service2.service.impl;

import com.isoft.c2team3service2.dto.ArtistDTO;
import com.isoft.c2team3service2.dto.FollowUserDTO;
import com.isoft.c2team3service2.entity.Artist;
import com.isoft.c2team3service2.entity.User;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.entity.UserFollow;
import com.isoft.c2team3service2.entity.UserFollowArtist;
import com.isoft.c2team3service2.mapper.*;
import com.isoft.c2team3service2.service.FollowService;
import com.isoft.c2team3service2.util.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FollowServiceImpl implements FollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;

    @Autowired
    private UserFollowArtistMapper userFollowArtistMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArtistMapper artistMapper;

    @Autowired
    private HeadMapper headMapper;

    @Override
    @Transactional
    public void followUser(Integer followedUserId) throws BusinessException {
        // 获取当前用户ID
        Integer currentUserId = UserHolder.getUser().getId();

        // 检查是否关注自己
        if (currentUserId.equals(followedUserId)) {
            throw new BusinessException("不能关注自己");
        }

        // 检查是否已经关注
        int followCount = userFollowMapper.checkFollowStatus(currentUserId, followedUserId);
        if (followCount > 0) {
            throw new BusinessException("已经关注该用户，不能重复关注");
        }

        // 执行关注操作
        userFollowMapper.insertFollowUser(currentUserId, followedUserId, LocalDateTime.now());
    }

    @Override
    @Transactional
    public void unfollowUser(Integer followedUserId) throws BusinessException {
        // 获取当前用户ID
        Integer currentUserId = UserHolder.getUser().getId();

        // 检查是否关注
        int followCount = userFollowMapper.checkFollowStatus(currentUserId, followedUserId);
        if (followCount == 0) {
            throw new BusinessException("尚未关注该用户，无法取消关注");
        }

        // 执行取消关注操作
        int deleteCount = userFollowMapper.deleteFollowUser(currentUserId, followedUserId);
        if (deleteCount == 0) {
            throw new BusinessException("取消关注失败");
        }
    }

    @Override
    @Transactional
    public void followArtist(Integer artistId) throws BusinessException {
        // 获取当前用户ID
        Integer currentUserId = UserHolder.getUser().getId();

        // 检查艺人是否存在
        Artist artist = artistMapper.selectById(artistId);
        if (artist == null) {
            throw new BusinessException("艺人不存在");
        }

        // 检查是否已经关注
        int followCount = userFollowArtistMapper.checkFollowStatus(currentUserId, artistId);
        if (followCount > 0) {
            throw new BusinessException("已经关注该艺人，不能重复关注");
        }

        // 执行关注操作
        userFollowArtistMapper.insertFollowArtist(currentUserId, artistId, LocalDateTime.now());
    }

    @Override
    @Transactional
    public void unfollowArtist(Integer artistId) throws BusinessException {
        // 获取当前用户ID
        Integer currentUserId = UserHolder.getUser().getId();

        // 检查是否关注
        int followCount = userFollowArtistMapper.checkFollowStatus(currentUserId, artistId);
        if (followCount == 0) {
            throw new BusinessException("尚未关注该艺人，无法取消关注");
        }

        // 执行取消关注操作
        int deleteCount = userFollowArtistMapper.deleteFollowArtist(currentUserId, artistId);
        if (deleteCount == 0) {
            throw new BusinessException("取消关注失败");
        }
    }

    @Override
    public List<FollowUserDTO> getFollowedUsers() {
        // 获取当前用户IDo
        Integer currentUserId = UserHolder.getUser().getId();

        // 获取关注的用户ID列表
        List<Integer> followedUserIds = userFollowMapper.selectFollowedIds(currentUserId);

        followedUserIds.forEach(s -> {
            System.out.println("________________"+ s);
        });

        if (followedUserIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 一次性查询所有用户信息，避免N+1查询问题
        List<User> users = userMapper.selectBatchIds(followedUserIds);

        return users.stream()
                .map(user -> {
                    FollowUserDTO f = new FollowUserDTO();
                    BeanUtils.copyProperties(user, f);

                    // 特别处理昵称 - 如果User实体中昵称字段名不同（如user.getName()）
                    // 根据实际情况调整这里的字段映射
                    // 假设User实体中昵称字段是name，需要手动设置到DTO的nickName
//                    if (user.getNickName() != null) {
//                        userDTO.setNickName(user.getNickName());
//                    }
                    f.setPho(headMapper.selectHead(user.getId()));

                    // 如果用户表和艺人表的昵称存储在不同地方，这里可以补充
                    // 例如：如果是艺人，可能需要从artist表获取艺名作为昵称
//                    if (user.getUserType() == 1 && user.getArtistId() != null) {
//                        Artist artist = artistMapper.selectById(user.getArtistId());
//                        if (artist != null) {
//                            userDTO.setArtistName(artist.getName());
//                            userDTO.setArtistBirthDate(artist.getBirthDate());
//                            userDTO.setGender(artist.getGender());
//                            userDTO.setNationality(artist.getNationality());
//                            userDTO.setAchievements(artist.getAchievements());
//                            userDTO.setWorks(artist.getWorks());
//
//                            // 如果艺人表有单独的昵称字段，这里可以设置
//                            if (userDTO.getNickName() == null) {
//                                userDTO.setNickName(artist.getName());
//                            }
//                        }
//                    }
//
                    // 设置角色信息
                    setUserRoles(user, f);

                    return f;
                })
                .collect(Collectors.toList());
    }


    // 设置用户角色
    private void setUserRoles(User user, FollowUserDTO f) {
        List<String> roles = new ArrayList<>();
        switch (user.getRoleId()) {
            case 1:
                roles.add("艺人");
                break;
            case 3:
                roles.add("普通用户");
                break;
            case 2:
                roles.add("会员");
                break;
            case 4:
                roles.add("管理员");
                break;
            default:
                roles.add("未知角色");
        }
        f.setRoles(roles);
    }

    @Override
    public List<ArtistDTO> getFollowedArtists() {
        Integer currentUserId = UserHolder.getUser().getId();
        List<ArtistDTO> artist1 = artistMapper.selectAll();
        // 调用修复后的方法，获取包含艺人ID和昵称的列表
        List<Map<String, Object>> followedArtists = userFollowArtistMapper.selectFollowedArtistsWithNickname(currentUserId);

        followedArtists.forEach(fo -> {
            System.out.println("--------------------" + fo);
        });

        if (followedArtists.isEmpty()) {
            return List.of();
        }

        // 转换为ArtistDTO列表
        return followedArtists.stream()
                .map(item -> {
                    Integer artistId = (Integer) item.get("artist_id");
                    String nickname = (String) item.get("nick_name");

                    // 查询艺人详细信息
                    ArtistDTO artist = artistMapper.selectArtistDTOById(artistId);
                    artist.setPho(headMapper.selectHead(artistId));
                    if (artist != null) {
                        artist.setNick_name(nickname); // 设置从用户表获取的昵称
                    }

                    artist.setRole("艺人");
                    return artist;

                })
                .filter(Objects::nonNull) // 过滤空值
                .collect(Collectors.toList());
    }
}
